from flask import Blueprint, request, render_template, jsonify, json, session, redirect
from models import Student, Homework, Copy
from collections import OrderedDict
from echarts import echarts as ec
# from django.core.paginator import Paginator  # 注释掉Django分页器
from Utils.paginator import SimplePaginator

bp = Blueprint("copy", __name__, url_prefix="/copy")


@bp.before_request
def before_request():
    """抄袭检测蓝图权限检查"""
    # 检查用户是否登录
    if session.get('is_login') != 'true':
        return redirect('/login')
    
    # 抄袭检测功能主要面向教师，但学生也可以查看自己的结果
    user_role = session.get('role')
    if user_role not in ['teacher', 'student']:
        return jsonify({'error': '用户角色无效'}), 403


@bp.route("/")
def student_index():
    return "这是抄袭显示界面"


@bp.route("/list")
def student_homework_list():
    print("查重列表")
    return render_template('copy.html')


# 显示各班抄袭版本
@bp.route("/list2")
def student_homework_list2():
    print("各班抄袭版本")
    return render_template('copy2.html')


@bp.route("/echarts")
def show_with_echarts():
    # 两个班班级号，did1表示只有一个班，did2表示有两个班
    ec.did1(a = 1)
    # ec.did2(a=1, b=4)
    return render_template('line_base.html')


@bp.route("/list1", methods=["GET"])
def homepage_list1():
    # 1。get查找 根据主键查找
    # teacher = Teacher.query.get(1001)
    # print(teacher.name)
    # 2。fliter_by查找
    # students = Student.query.filter_by(class_id = "230101")
    hid = request.args.get("hid")
    print(hid)
    if hid is not None:
        copys = Copy.query.filter_by(hid=hid).all()
    else:
        copys = Copy.query.all()
    pageIndex = request.args.get("pageIndex")
    pageSize = request.args.get("pageSize")
    out_data = []
    data = []
    i = 0
    for copy in copys:
        data.append(copy.to_json())
        i += 1
    paginator = SimplePaginator(data, pageSize)
    page_data = paginator.page(pageIndex)
    out_data = page_data
    return OrderedDict(code=0, count=i, data=out_data)


@bp.route("/list2", methods=["GET"])
def homepage_list2():
    # 1。get查找 根据主键查找
    # teacher = Teacher.query.get(1001)
    # print(teacher.name)
    # 2。fliter_by查找
    # students = Student.query.filter_by(class_id = "230101")
    hid = request.args.get("hid")
    print(hid)
    if hid is not None:
        copys = Copy.query.filter_by(hid=hid).all()
    else:
        copys = Copy.query.all()
    pageIndex = request.args.get("pageIndex")
    pageSize = request.args.get("pageSize")
    out_data = []
    data = []
    i = 0
    for copy in copys:
        data.append(copy.to_json())
        i += 1
    paginator = SimplePaginator(data, pageSize)
    page_data = paginator.page(pageIndex)
    out_data = page_data
    return OrderedDict(code=0, count=i, data=out_data)
